package org.example.springtest.controller;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.Valid;
import org.example.springtest.model.dto.responseMessage;
import org.example.springtest.model.dto.user.LoginResponse;
import org.example.springtest.model.dto.user.LoginRequest;
import org.example.springtest.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Objects;

@RestController
@RequestMapping("/user")
public class UserController {
    private final UserService userService;
    public UserController(UserService userService) {
        this.userService = userService;
    } 
    @PostMapping(value = "/login")
    public responseMessage<LoginResponse> login(@Valid @RequestBody LoginRequest request, HttpServletRequest httpRequest) {
//      httpRequest.getAttribute("userId")
        LoginResponse user = userService.login(request.getLoginAccount(), request.getLoginPassword());
        if (Objects.isNull(user)) return responseMessage.error(500, "用户名或密码错误");
        return responseMessage.success(user);
    }
    @PostMapping(value = "/loginOut")
    public responseMessage<Object> loginOut(HttpServletRequest httpRequest) {
        String userId = (String) httpRequest.getAttribute("userId");
        boolean isDelect =  userService.loginOut(userId);
        return isDelect? responseMessage.success(null) : responseMessage.error(500, "操作失败");
    }
}
